<?php


namespace Biz\service\advertisement\position;

use Biz\model\advertisement\MHhzPositionUserprofile;
use Biz\model\advertisement\MPositionAdType;
use Biz\service\advertisement\AdUserProfileManagement;
use Doraemon\service\position\DisplayConstInterface;
use Doraemon\tools\HhzEnv;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Exception;

class BizPositionUserprofile extends BizPositionPageTpl
{
    const TPL_CONFIG_TPL_NAME = '用户分群配置';
    private array $group;
    private bool $showField;

    public function getList(): array
    {
        $entity = new MHhzPositionUserprofile;

        $params = $this->getRequest()->all();
        $sign = $params['sign'] ?? $entity::SIGN_TYPE_FIELD;
        $sort = strlen($params['field']) == 0;
        $this->showField = $sign == $entity::SIGN_TYPE_FIELD;

        $labels = [];
        $groups = [];
        $fields = [];
        $list = AdUserProfileManagement::getConf();
        if ($list) {
            foreach ($list as $k => $v) {
                $v['id'] = $k;
                if ($v['sign'] == $entity::SIGN_TYPE_GROUP) {
                    $group[$v['column_field']] = $v['column_name'];
                    $groups[] = $v;
                } elseif ($v['sign'] == $entity::SIGN_TYPE_LABEL) {
                    $labels[] = $v;
                }else {
                    $fields[$v['group_field']][] = $v;
                }
            }
        }
        $group[''] = '-';
        $this->group = $group;
        $list = [];
        if ($sign == $entity::SIGN_TYPE_FIELD) {
            foreach ($group as $column_field => $name) {
                $list = array_merge($list, $fields[$column_field] ?? []);
            }
        }

        if ($sign == $entity::SIGN_TYPE_LABEL) $list = $labels;
        if ($sign == $entity::SIGN_TYPE_GROUP) $list = $groups;
        $manageList = [];
        foreach ($list as $v) {
            if (isset($v['column_alias'])) {
                $bool = $params['field'] && (strpos($v['column_field'], $params['field']) === false) && (strpos($v['column_alias'], $params['field']) === false);
            } else {
                $bool = $params['field'] && (strpos($v['column_field'], $params['field']) === false);
            }
            if ($bool) continue;
            $manageList[] = $v;
        }
        return $manageList;
    }

    public function getTotal(): int
    {
        return 0;
    }

    public function condition(): array
    {
        $tab = $this->getRequest()->input('tab', '');
        $condition = [];

        if ($tab) $condition['tab'] = $tab;

        return $condition;
    }

    public function withInfoHtml(): array
    {
        $aliasPath = AdUserProfileManagement::ALIAS_PATH;
        $confPath = AdUserProfileManagement::CONF_PATH;
        $aliasScript = "/data/wwwroot/g_biz/cli/ad/userprofileMakeAlias.php";
        $createScript = "/data/wwwroot/g_biz/cli/ad/userprofileCreate.php";
        $hitScript = "/data/wwwroot/g_biz/cli/ad/userprofileHit.php";
        $esScript = "/data/wwwroot/g_biz/cli/ad/userprofileEs.php";

        $html = [
            '开发步骤 : ',
            "1.online环境通过脚本 php {$aliasScript} 获取配置,写入dev环境 {$aliasPath}",
            "2.dev环境通过脚本 php {$createScript} 生成配置,从开发机下载 {$confPath}",
            "3.检查form显示, 方法入口:\Doraemon\service\position\UserProfileModule::formDisplay",
            "4.检查form保存, 方法入口:\Doraemon\service\position\AdmOperationModule::addUserProfile",
            "5.检查grid显示, 方法入口:\Doraemon\service\position\UserProfileModule::display",
            "6.检查单点匹配, php {$hitScript} 5204625 20 9,10 \"is_advisory:1;action_interest_tag_1m:家饰搭配;\"",
            "7.检查es查询uid, php {$esScript} 9,10 20 1 5000",
        ];
        return ["提示", implode("<br/>", $html)];
    }


    public function getGrid(Grid $grid)
    {
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->disablePagination();
        $grid->disableActions();
        $grid->filter(function (Grid\Filter $filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            $filter->equal('sign', '类型')->select(MHhzPositionUserprofile::SIGN_TYPE_MAP)->default(MHhzPositionUserprofile::SIGN_TYPE_FIELD);
            $filter->equal('field', '标识/别名');
            //条件展开
            $filter->expand();
        });

        $grid->column('id', '配置ID')->sort();
        $grid->column('info', '信息')->display(function () {
            /**
             * @var MHhzPositionUserprofile $this
             */
            $display = [
                '标识 : ' . $this->column_field,
                '名称 : ' . $this->column_name,
            ];
            if ($this->column_alias) $display[] = '别名 : ' . $this->column_alias;
            return implode('<br/>', $display);
        });
        $grid->column('show_option', '加载显示')->select(MHhzPositionUserprofile::SHOW_OPTION_MAP);
        if ($this->showField) {
            $grid->column('group_field', '组信息')->select($this->group);
            $grid->column('form_type', '表单类型')->select(DisplayConstInterface::ADM_FORM_TYPE_MAP);
            $grid->column('switch_name', '开关名称')->editable();
            $grid->column('form_help', '帮助描述')->width(300)->editable();
        }
    }

    public function getForm(Form $form)
    {
        $form->hidden('id');
        $form->text('column_field', '标识')->required();
    }

    public function getFormInfo($id): array
    {
        return MPositionAdType::getById($id);
    }

    /**
     * @throws Exception
     */
    public function save($input)
    {
        if (!HhzEnv::isShopTest()) throw new Exception('仅限环境操作');
        $id = $input['id'] ?? 0;
        $column_field = $input['column_field'] ?? '';
        \Biz\service\advertisement\AdUserProfileManagement::createField($column_field);
    }

    public function delete($id): int
    {
        return 0;
    }

    public function sort($input)
    {
        if ($input) {
            AdUserProfileManagement::sort($input);
        }
    }

    /**
     * @throws Exception
     */
    public function put($input, $id)
    {
        $name = $input['name'] ?? '';
        $value = $input['value'] ?? '';
        $id = $input['pk'] ?? $id;
        $data = [];
        if (isset($input['group_field'])) {
            $name = 'group_field';
            $value = $input['group_field'];
        }
        if (isset($input['show_option'])) {
            $name = 'show_option';
            $value = $input['show_option'];
        }
        if (isset($input['form_type'])) {
            $name = 'form_type';
            $value = $input['form_type'];
        }
        switch ($name) {
            case 'form_type':
                $data['form_type'] = $value;
                break;
            case 'show_option':
                $data['show_option'] = $value;
                break;
            case 'group_field':
                $data['group_field'] = $value;
                break;
            case 'switch_name':
                $data['switch_name'] = $value;
                break;
            case 'form_help':
                $data['form_help'] = $value;
                break;
            default:
                throw new \Exception('未定义的快速更新字段');
        }

        if (is_numeric($id) && $data) {
            $conf = AdUserProfileManagement::getConf();
            if (!isset($conf[$id])) throw new \Exception('配置缺失');
            $conf[$id] = $data + $conf[$id];
            AdUserProfileManagement::setConf($conf);
        }
    }
}